﻿namespace ThreeByte.ActiveDeck.Dashboard
{
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using System;
    using ActiveDeck.Dashboard.LoginUI;
    using ThreeByte.ActiveDeck.Web.Services;
    using System.ServiceModel.DomainServices.Client;
    using ThreeByte.ActiveDeck.Web.Models;
    using System.Xml.Linq;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using System.Linq;
    using System.IO;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Home page for the application.
    /// </summary>
    public partial class Resources : Page
    {

        public static readonly XNamespace NAMESPACE = @"http://www.activedeck.com/PowerPoint/";
        public static readonly XNamespace ns = NAMESPACE;

        /// <summary>
        /// Creates a new <see cref="Inspect"/> instance.
        /// </summary>
        public Resources() {
            InitializeComponent();
           
        }

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e) {
            //Get the Query parameters

            string resource = null;

            if(this.NavigationContext.QueryString.ContainsKey("pres")){
                currentPresentationId = this.NavigationContext.QueryString["pres"];
            }
            if(this.NavigationContext.QueryString.ContainsKey("res")) {
                resource = this.NavigationContext.QueryString["res"];
            }

            if(currentPresentationId != null && resource != null) {
                LoadResource(currentPresentationId, Guid.Parse(resource));
            }
            //} else if(currentPresentationId != null) {
            //    LoadPresentationResources(currentPresentationId);
            //} else {
            //    //InspectorBox.Selection.Text = "Invalid navigation request";
            //}

            DashboardDataSource.QueryParameters.Add(new Parameter() { ParameterName = "presentationId", Value = currentPresentationId });
            DashboardDataSource.Load();
            
        }

        private DashboardDataContext ctx = new DashboardDataContext();
        private string currentPresentationId;

        //private void LoadPresentationResources(string pres) {

        //    //Load the Outline of the presentation

            

        //    //ctx.GetResourceInfosQuery
        //    //EntityQuery<PresentationConfig> q = ctx.GetPresentationConfigQuery(pres);
        //    //ctx.Load(q, PresentationDataLoadComplete, pres); 

        //}

        //private void PresentationDataLoadComplete(LoadOperation<PresentationConfig> op) {

        //    //After we got the PresentationConfig, do something with it
        //    if(op.HasError) {
        //        //Handle this
        //        //InspectorBox.Selection.Text = string.Format("Error loading presentation: {0}", op.Error.Message);
        //        return;
        //    }

        //    DisplayPresentation(op.Entities.FirstOrDefault());
        //}

        //private void DisplayPresentation(PresentationConfig config) {

        //    XElement el = XElement.Parse(config.XML);
        //    XElement resElement = el.Element(ns + "Resources");

        //    string stringToFormat = resElement.ToString();

        //    //Replace xml entity representations in base text
        //    stringToFormat = stringToFormat.Replace("<", "&lt;").Replace(">", "&gt;");

        //    //Do a regex replace for Resources
        //    string regex = @"ID=""(?<resid>.{36})"""; //Guids are always 36 characters long (including dashes)
        //    string linkReplacement = string.Format(@"ID=""<Hyperlink NavigateUri=""/Resources/{0}/${{resid}}"" >${{resid}}</Hyperlink>""", config.PresentationID);
        //    stringToFormat = Regex.Replace(stringToFormat, regex, linkReplacement);

        //    stringToFormat = string.Format("<Paragraph>{0}</Paragraph>", stringToFormat);
        //    stringToFormat = string.Format("<Section xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{0}</Section>", stringToFormat);

        //    //InspectorBox.Xaml = stringToFormat;
        //}


        private void LoadResource(string pres, Guid resId) {

            //InspectorBox.Selection.Text = string.Format("Loading Presentation {0} Resource {1}...", pres, resource);

            ctx.GetResource(pres, resId, LoadResource_Complete, resId);

        }

        private void LoadResource_Complete(InvokeOperation<byte[]> op) {
            if(op.HasError) {
                return;
            }
            DisplayCanvas.Children.Clear();

            try {
                //Load the content (Image?)
                MemoryStream imageContent = new MemoryStream(op.Value);

                BitmapImage newImage = new BitmapImage();
                newImage.SetSource(imageContent);

                DisplayCanvas.Children.Add(new Image() { Source = newImage });
            } catch(Exception) {

            }
        }

        private void PreviewResource_Click(object sender, System.Windows.RoutedEventArgs e) {
            //Do the load here
            //Get the ID of the resource and then load it below

            HyperlinkButton button = (HyperlinkButton)sender;
            Guid resId = (Guid)(button.Tag);

            LoadResource(currentPresentationId, resId);
        }


        //private void DownloadSchemaButton_Click(object sender, System.Windows.RoutedEventArgs e) {
        //    PresentationConfig configToSave = CachedPresentationConfig;
        //    if(configToSave == null) {
        //        //Cannot save it if it han't been downloaded
        //        return;
        //    }

        //    SaveFileDialog saveDialog = new SaveFileDialog();
        //    saveDialog.DefaultExt = "xml";
        //    saveDialog.Filter = "XML Files|*.xml|All Files|*.*";
        //    if(saveDialog.ShowDialog() ?? false) {
        //        using(StreamWriter sw = new StreamWriter(saveDialog.OpenFile())){
        //            sw.Write(CachedPresentationConfig.XML);
        //        }
        //    }

        //}

    }
}